package com.uminho.egendme;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.json.JSONException;
import org.w3c.dom.Text;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.exceptions.DestroyException;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.exceptions.NotAllowedError;
import com.uminho.exceptions.OAuthServiceFailureError;
import com.uminho.exceptions.SaveException;
import com.uminho.http.InternalStorage;
import com.uminho.http.Webservice;
import com.uminho.objects.Service;
import com.uminho.service.ServiceCalendar;

public class Search extends Activity {

	Dialog dialog;
	Webservice w;
	ArrayList<Service> services;
	ProgressDialog myProgressDialog = null; 
	Handler messages;
	ListView list;
	int page=1;
	Button moreresults;
	String namef, tagsf, categoryf, addressf, orderf;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		final double lat = getIntent().getDoubleExtra("lat", 0.0);
		final double lon = getIntent().getDoubleExtra("lon", 0.0);

		list = (ListView) findViewById(R.id.list);

		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		moreresults = (Button) findViewById(R.id.moreresults);
		moreresults.setVisibility(View.INVISIBLE);

		moreresults.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				page=page+1;
				new Thread() {

					@Override
					public void run() {


						w = Webservice.getInstance();
						try {
							try {
								services.addAll( w.SearchService(page+"",namef ,tagsf , categoryf, lon+"", lat+"", addressf,"asc",orderf));
								messages.sendEmptyMessage(1);
							} catch (SaveException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (DestroyException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							}
						} catch (NumberFormatException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (MalformedURLException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (IOException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (InvalidOAuthParametersError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (InvalidOAuthTokenError e) {
							messages.sendEmptyMessage(-1);
							e.printStackTrace();
						} catch (OAuthServiceFailureError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (NotAllowedError e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (URISyntaxException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						} catch (JSONException e) {
							messages.sendEmptyMessage(0);
							e.printStackTrace();
						}


						// dismiss the progress dialog
						myProgressDialog.dismiss();


					}

				}.start();


			}});

		actionBar.setHomeAction(new Action() {

			public void performAction(View view) {
				Intent i = new Intent(Search.this, Dashboard.class);
				startActivity(i);
			}

			public int getDrawable() {
				return R.drawable.icon1;
			}
		});
		actionBar.setTitle(R.string.search);


		actionBar.addAction(new SearchAction(R.drawable.ic_action_search));

		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				ServiceDialog service = new ServiceDialog(Search.this,services.get(position), null);
				service.show();

				
				if(services.get(position).getIsPartner()){
					final int positionf = position;
					new Thread() {

						@Override
						public void run() {
							w = Webservice.getInstance();
							try {
								try {
									w.clickPartnerService(services.get(positionf).getId());
									Log.d("partnerService","View");
								} catch (SaveException e) {								
							
									e.printStackTrace();
								} catch (DestroyException e) {
									e.printStackTrace();
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (MalformedURLException e) {
							} catch (IOException e) {
								e.printStackTrace();
							} catch (InvalidOAuthParametersError e) {
								e.printStackTrace();
							} catch (InvalidOAuthTokenError e) {
								e.printStackTrace();
							} catch (OAuthServiceFailureError e) {
								e.printStackTrace();
							} catch (NotAllowedError e) {
								e.printStackTrace();
							} catch (URISyntaxException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}

					}.start();
				}

			}
		});


		messages = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				if(msg.what==1){
					Log.d("size", services.size()+"");
					if(services.size()>=9){
						moreresults.setVisibility(View.VISIBLE);
					}else{
						moreresults.setVisibility(View.INVISIBLE);
					}
					list.setAdapter(new ImageAndTextAdapter(Search.this, R.layout.favorites_row, services));
					// dismiss the progress dialog
					myProgressDialog.dismiss();
				}else if(msg.what==0){
					Toast.makeText(Search.this, R.string.unknownerrorinternetconnection, Toast.LENGTH_LONG);
					// dismiss the progress dialog
					myProgressDialog.dismiss();
				}else{
					InternalStorage.deleteToken();
					Intent i = new Intent(Search.this,Login.class);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
					// dismiss the progress dialog
					myProgressDialog.dismiss();
				}
			}};

			Context context = Search.this;
			dialog = new Dialog(context);

			dialog.setContentView(R.layout.searchdialog);
			dialog.setTitle(this.getResources().getString(R.string.refineSearch));

			final EditText nameEdit = (EditText)dialog.findViewById(R.id.name);
			final EditText tagsEdit = (EditText)dialog.findViewById(R.id.tags);
			final EditText addressEdit = (EditText)dialog.findViewById(R.id.address);
			final CheckBox cl = (CheckBox)dialog.findViewById(R.id.checkLocation);
			cl.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					addressEdit.setEnabled(!isChecked);

					addressEdit.clearFocus();
					addressEdit.setText("");

				}
			});
			final Spinner categorySpinner = (Spinner) dialog.findViewById(R.id.category);
			final Spinner orderBySpinner = (Spinner) dialog.findViewById(R.id.order);

			ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
					this, R.array.categorieslist, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			ArrayAdapter<CharSequence> adapterOrder = ArrayAdapter.createFromResource(
					this, R.array.searchorder, android.R.layout.simple_spinner_item);
			adapterOrder.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			categorySpinner.setAdapter(adapter);
			orderBySpinner.setAdapter(adapterOrder);

			Button submit = (Button) dialog.findViewById(R.id.submit);
			submit.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					dialog.dismiss();
					page=1;
					String name,tags,address,category, order;
					name=tags=address=category="";

					name = nameEdit.getText().toString();
					tags = tagsEdit.getText().toString();
					address = addressEdit.getText().toString();
					category = categorySpinner.getSelectedItemPosition()+"";
					order = orderBySpinner.getSelectedItem().toString();
					namef=name;
					tagsf=tags; 
					addressf=address; 
					if(category.compareTo("0")==0){
						categoryf=null;
					}else{
						categoryf=category;	
					}
					switch(orderBySpinner.getSelectedItemPosition()){
					case 0 : orderf = "name";break;
					case 1 : orderf = "rating";break;
					default: orderf = null;

					}



					myProgressDialog = ProgressDialog.show(Search.this,getString(R.string.loading), getString(R.string.getsearch), true); 

					new Thread() {

						@Override
						public void run() {


							w = Webservice.getInstance();
							try {
								try {
									services = w.SearchService(page+"",namef ,tagsf , categoryf, lon+"", lat+"", addressf,"asc",orderf);
									Log.d("search input",page+" - "+namef+" - "+tagsf+" - "+addressf+" - "+categoryf+"-"+orderf);

									messages.sendEmptyMessage(1);
								} catch (SaveException e) {
									messages.sendEmptyMessage(0);
									e.printStackTrace();
								} catch (DestroyException e) {
									messages.sendEmptyMessage(0);
									e.printStackTrace();
								}
							} catch (NumberFormatException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (MalformedURLException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (IOException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (InvalidOAuthParametersError e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (InvalidOAuthTokenError e) {
								messages.sendEmptyMessage(-1);
								e.printStackTrace();
							} catch (OAuthServiceFailureError e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (NotAllowedError e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (URISyntaxException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							} catch (JSONException e) {
								messages.sendEmptyMessage(0);
								e.printStackTrace();
							}


						}

					}.start();



				}
			});

			dialog.show();

	}

	private class SearchAction extends AbstractAction {

		public SearchAction(int iconId) {
			super(iconId);
		}

		public void performAction(View view) {
			dialog.show();

		}

	}

	public class ImageAndTextAdapter extends ArrayAdapter<Service> {

		private LayoutInflater mInflater;

		private ArrayList<Service> mlistServices;
		private TypedArray mIcons;

		private int mViewResourceId;

		public ImageAndTextAdapter(Context ctx, int viewResourceId,
				ArrayList<Service> listServices) {
			super(ctx, viewResourceId, listServices);

			mInflater = (LayoutInflater)ctx.getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);

			mlistServices = listServices;


			mViewResourceId = viewResourceId;
		}

		@Override
		public int getCount() {
			return mlistServices.size();
		}

		@Override
		public Service getItem(int position) {
			return mlistServices.get(position);
		}

		@Override
		public long getItemId(int position) {
			return mlistServices.get(position).getId();//fazer isto
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = mInflater.inflate(mViewResourceId, null);


			ImageView iv = (ImageView)convertView.findViewById(R.id.image);
			iv.setImageDrawable(mlistServices.get(position).getAvatar());

			TextView tv = (TextView)convertView.findViewById(R.id.favorite_row_title);
			tv.setText(mlistServices.get(position).getName());


			TextView td = (TextView) convertView.findViewById(R.id.favorite_row_description);
			td.setText(mlistServices.get(position).getDescription());

			if(mlistServices.get(position).getIsPartner()){
				tv.setTypeface(Typeface.DEFAULT_BOLD);
				td.setTypeface(Typeface.DEFAULT_BOLD);
				//convertView.setBackgroundResource( );
			}

			return convertView;
		}





	}

}
